package com.awardsystem.Utils;

import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;

/** 全局异常处理 **/
@RestControllerAdvice
public class ExcHandler {
    @ExceptionHandler(value = {Exception.class, com.awardsystem.Utils.OperationFailed.class})
    public JSONObject errorHandler(Exception ex) {
        JSONObject map = new JSONObject();
        map.put("success", false);
        map.put("exc", getExcMsg(ex));
        return map;
    }
    private String getExcMsg(Exception e){
        if(e instanceof com.awardsystem.Utils.OperationFailed)return e.toString();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(os);
        e.printStackTrace(ps);
        return new String(os.toByteArray(), StandardCharsets.UTF_8);
    }
}
